<template>
  <div id="mention-modal" :style="{ top: top, left: left }">
    <input id="mention-input" ref="input" v-model="searchVal" placeholder="输入名称查询" @keyup="inputKeyupHandler" />
    <ul id="mention-list">
      <li
        v-for="item in searchedList"
        :key="item.id"
        @click="insertMentionHandler(item.id, item.name)"
      >{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MentionModal',
  props: {
    roles: {
      type: Array,
      default: () => []
    },
    position: {
      type: Object,
      default: () => { return { top: '0px', left: '0px', bottom: '0px', right: '0px' } }
    }
  },
  data() {
    return {
      // list 信息
      searchVal: '',
      top: '0px',
      left: '0px'
    }
  },
  computed: {
    // 根据 <input> value 筛选 list
    searchedList() {
      const searchVal = this.searchVal.trim().toLowerCase()
      return this.roles.filter(item => {
        const name = item.name.toLowerCase()
        if (name.indexOf(searchVal) >= 0) {
          return true
        }
        return false
      })
    }
  },
  mounted() {
    // 获取光标位置
    const domSelection = document.getSelection()
    const domRange = domSelection?.getRangeAt(0)
    if (domRange == null) return
    const rect = domRange.getBoundingClientRect()
    console.log(domSelection, domRange, rect, 8989)
    // 定位 modal
    this.top = `${rect.top - 230 + 20}px`
    this.left = `${rect.left - 255 - 120 + 5}px`
    // focus input
    this.$refs.input.focus()
  },
  methods: {
    inputKeyupHandler(event) {
      // esc - 隐藏 modal
      if (event.key === 'Escape') {
        this.$emit('hideMentionModal')
      }
      // enter - 插入 mention node
      if (event.key === 'Enter') {
        // 插入第一个
        const firstOne = this.searchedList[0]
        if (firstOne) {
          const { id, name } = firstOne
          this.insertMentionHandler(id, name)
        }
      }
    },
    insertMentionHandler(id, name) {
      this.$emit('insertMention', id, name)
      this.$emit('hideMentionModal') // 隐藏 modal
    }
  }

}
</script>

<style scoped lang="scss">
#mention-modal {
  position: absolute;
  background-color: #121418;
  padding: 8px;
  box-sizing: border-box;
  color: #fff;
  z-index: 99999;
  max-height: 200px;
  overflow-y: auto;
  border-radius: 4px;
}
#mention-modal input {
  width: 100px;
  outline: none;
}
#mention-modal ul {
  padding: 0;
  margin: 0;
}
#mention-modal ul li {
    list-style: none;
    cursor: pointer;
    padding: 3px 0;
    text-align: left;
}

#mention-modal ul li:hover {
    text-decoration: underline;
}
</style>
